define(['Util',
    '../common/getMenu',
    'list',
    'cookie',
    'form',
    'text!tpl/order/viewOrder.tpl',
    'text!tpl/order/assigned.tpl',
    'dialog',
    'select',
    'tab',
    'loading',
    '../common/getPath',
    '../common/getQueryString',
    'date',
    'process',
    'provincesSelect',
    'comboSelect',
    'validator',
    '../common/getQueryString',
    '../common/dateFormat'  
],
function(Util, getMenu, List, $cookie, Form, tpl,AssignedTpl, Dialog, Select, Tab, Loading, AjaxPath, GetQueryString, MyDate,Process,provincesSelect,ComboSelect,Validator,getQueryString) {
    require(['style!css/style.css','style!css/step.css']);

    var $el = null;

    var _indexModule = null,
        list = null,
        tplId = null,
        tab = null,
        handLoading = null,
        process = null,
        telss = null,
        optionsData = null,
        htAssignedSelect = null,
        editOrderData = null,
        htOrderStatus = null,
        htAssignedSelectKey = null,
        htAssignedDataList = null,
        optionsDataID = null, 
        dialog = null;
    var initialize = function(indexModule, options, tabItem) {
        $el = $(tpl);
        _indexModule = indexModule;
         this.content = $el;
        // 事件--点击切换tab后事件回调
        $(tabItem).on("tabActive", function() {
            tabItem.show(true); // 刷新表单
        });

        tab = tabItem;
        //createLoading();
        tplId = options.menuId;
        optionsData = options;
        optionsData.menuId = "orderList"
        optionsDataID = (getQueryString("from") ? getQueryString("id") : optionsData.id);
        
        // 业务相关代码
        eventInit();
    	//附件
		appendixInit();
		//获取工单数据
		viewOrderInfo();
    };

    var eventInit = function (){
        //页面除dialog按钮功能
        $el.on('click', '.htApproved', htApproved);//审批通过
        $el.on('click', '.htRejected', htRejected);//驳回
        $el.on('click', '.htWithdraw', editOrderDialog);//撤回  按钮跳修改页面
        $el.on('click', '.htAssigned', htAssigned);//指派
        $el.on('click', '.htSubmit', htSubmit);//提交

    };
   
    
    //权限按钮
    var htBtnBack = function(oData,status){
    	var userId=$cookie.get("userId")-0;
        var orderPersonId=oData.orderPersonId; //提出人；
        var assignPerson=oData.assignPerson;   //审批人；orderStatus
        var orderStatus=status;   //状态；orderStatus
        var htmls = '';
        if(orderStatus ===2 || orderStatus ===3){
        	if(assignPerson == userId){
        		htmls +='<a href="javascript:;" class="t-btn t-btn-white htApproved mr-10">审批通过</a>'+
						'<a href="javascript:;" class="t-btn t-btn-white htRejected mr-10">驳回</a>'+
						'<a href="javascript:;" class="t-btn t-btn-white htAssigned mr-10">指派</a>'
        	}
		}else if(orderStatus ===4){
			if(assignPerson == userId){
        		htmls +='<a href="javascript:;" class="t-btn t-btn-white htApproved mr-10">审批通过</a>'+
						'<a href="javascript:;" class="t-btn t-btn-white htRejected mr-10">驳回</a>'+
						'<a href="javascript:;" class="t-btn t-btn-white htAssigned mr-10">指派</a>'
        	}
		}else if(orderStatus ===5){
			if(assignPerson == userId){
        		htmls +='<a href="javascript:;" class="t-btn t-btn-white htApproved mr-10">发货</a>'+
						'<a href="javascript:;" class="t-btn t-btn-white htRejected mr-10">驳回</a>'+
						'<a href="javascript:;" class="t-btn t-btn-white htAssigned mr-10">指派</a>'
        	}
		}else if(orderStatus ===6){
			if(orderPersonId == userId){
        		htmls +='<a href="javascript:;" class="t-btn t-btn-white htApproved mr-10">确认</a>'
        	}
		}else if(orderStatus ===1){
			if(orderPersonId == userId){
				htmls +='<a href="javascript:;" class="t-btn t-btn-white htWithdraw mr-10">修改</a>'+
						'<a href="javascript:;" class="t-btn t-btn-white htSubmit mr-10">提交</a>'
			}
			
		}else{
			htmls = '';
		}
		$('.htBtnBack',$el).html(htmls);
    };
    //提交
    var htSubmit = function(){
    	$('.htBtnBack',$el).html('');
		Util.ajax.getJson(AjaxPath.management+"/order/updateStatus?operation=0&id="+optionsDataID,{}, function(result, isok) {
    		if(result.returnCode === "0000"){
    			htOrderStatus = result.beans.status;
                new Dialog({
				    mode: 'tips',
				    delayRmove:1.5, //延迟删除秒数设定 tips默认3秒,非tips默认不关闭。
				    tipsType:'success', //tips类型；可选 success | error，默认普通tips。
				    width:320,
				    height:180,
				    content: '<div style="text-align:center;margin-top:90px">' + result.beans.sucess + '</div>'
				});
                setTimeout(function(){
	    		 	//步骤条显示
	                for(var i=0;i<$('.htWhether',$el).length;i++){
	    		 		$('.htWhether',$el).eq(i).removeClass('step-done').removeClass('step-current');
	    		 	}
	    		 	for(var i=0;i<result.beans.status;i++){
	    		 		$('.htProcessOl li .htWhether',$el).eq(i).addClass('step-done');
	    		 	}
	    		 	if(result.beans.status === 7){
	    		 		$('.htProcessOl .step-last .htWhether').addClass('step-current');
	    		 	}
	    		 	//$('.htWhether',$el).eq(result.beans.status-1).addClass('step-current');
	    		 	htBtnBack(result.beans,result.beans.status);
                },1500);
    		}else{
    			new Dialog({
				    mode: 'tips',
				    delayRmove:1.5, //延迟删除秒数设定 tips默认3秒,非tips默认不关闭。
				    tipsType:'success', //tips类型；可选 success | error，默认普通tips。
				    width:320,
				    height:180,
				    content: '<div style="text-align:center;margin-top:90px">' + result.returnMessage + '</div>'
				});
    		}
		},'application/json');
    }
    
    //获取工单
    var viewOrderInfo = function(){
    	Util.ajax.getJson(AjaxPath.management + "/order/findOrder?id="+optionsDataID, function(result, isok){
    	//Util.ajax.getJson(AjaxPath.management + "/order/findOrder?id=1", function(result, isok){
    		//debugger;
    		 if (result.returnCode === "0000") {
    		 	editOrderData = result.bean;
    		 	htOrderStatus = result.bean.orderStatus;
    		 	htBtnBack(editOrderData,editOrderData.orderStatus);
    		 	
		 		//判断是否显示二级经理
    		 	if(result.bean.taxTotal<100000){
    		 		
    		 		$('.htTaxTotalEr',$el).hide();
    		 		for(let i=0;i<7;i++){
    		 			$('.htWhether1 .step-num',$el).eq(i).html(i+1);
    		 		}
    		 	}
    		 	//步骤条显示
    		 	if(result.bean.orderStatus !== 1){
    		 		for(var i=0;i<(result.bean.orderStatus);i++){
        		 		$('.htProcessOl li .htWhether',$el).eq(i).removeClass('step-done').removeClass('step-current').addClass('step-done');
        		 	}
    		 		if(result.bean.orderStatus === 7){
        		 		$('.htProcessOl .step-last .htWhether').addClass('step-current');
        		 	}
    		 	}
    		 	//$('.htProcessOl li .htWhether',$el).eq(result.bean.orderStatus-1).removeClass('step-done').removeClass('step-current').addClass('step-current');
    		 	//赋值	
    		 	for(let keys in result.bean){
					if($('.htOrderFrom',$el).find('input[name="'+keys+'"]')){
						$('.htOrderFrom',$el).find('input[name="'+keys+'"]').val($.trim(result.bean[keys]));
						if(keys === 'orderTime' || keys === 'deliveryFirstTime' || keys === 'deliveryLastTime'){
							var htTime = htTimeConversion(result.bean[keys]);
							$('.htOrderFrom',$el).find('input[name="'+keys+'"]').val(htTime);	
						}
					}
	        	}
    		 	//判断需求单位
    		 	if(result.bean.demandEmployer === 0){//分公司自用
    		 		$('.ifShow',$el).show();//空li
    		 		for(var i=0;i<$('.htWhetherHide',$el).length;i++){
    		 			$('.htWhetherHide',$el).hide();
    		 		}
    		 	}else if(result.bean.demandEmployer === 1){//客户采购
    		 		$('.ifShow',$el).hide();
    		 		//判断是否显示合同编号合同名称
    		 		if(result.bean.contractStatus === 0){
    		 			for(var i=0;i<$('.htWhetherShow',$el).length;i++){
    		 				$('.htWhetherShow',$el).show();
    		 			}
    		 		}else{
    		 			for(var i=0;i<$('.htWhetherShow',$el).length;i++){
        		 			$('.htWhetherShow',$el).hide();
        		 		}
    		 		}
    		 	}
            } else {
               new Dialog({
				    mode: 'tips',
				    delayRmove:1.5, //延迟删除秒数设定 tips默认3秒,非tips默认不关闭。
				    tipsType:'success', //tips类型；可选 success | error，默认普通tips。
				    width:320,
				    height:180,
				    content: '<div style="text-align:center;margin-top:90px">' + result.returnMessage + '</div>'
				});
            }
    		
    	})
    }
    //时间戳转换
    var htTimeConversion = function getMyDate(str){  
        var oDate = new Date(str),  
        oYear = oDate.getFullYear(),  
        oMonth = oDate.getMonth()+1,  
        oDay = oDate.getDate(),  
        //oHour = oDate.getHours(),  
        //oMin = oDate.getMinutes(),  
        //oSen = oDate.getSeconds(),  
        oTime = oYear +'-'+oMonth+'-'+oDay;
        //oTime = oYear +'-'+oMonth+'-'+oDay +' '+oHour+':'+oMin+':'+oSen;//最后拼接时间  
        return oTime;  
    }; 
    //审批通过
    var htApproved = function(i){
    	$('.htBtnBack',$el).html('');
    	Util.ajax.getJson(AjaxPath.management + "/order/updateStatus?operation=0&id="+optionsDataID, {}, function(result, isok){
		//Util.ajax.getJson(AjaxPath.management + "/order/updateStatus?operation=0&id=3", {}, function(result, isok){
    		 if (result.returnCode === "0000") {
    		 	htOrderStatus = result.beans.status
                new Dialog({
				    mode: 'tips',
				    delayRmove:1.5, //延迟删除秒数设定 tips默认3秒,非tips默认不关闭。
				    tipsType:'success', //tips类型；可选 success | error，默认普通tips。
				    width:320,
				    height:180,
				    content: '<div style="text-align:center;margin-top:90px">' + result.beans.sucess + '</div>'
				});
                setTimeout(function(){
	                //步骤条显示
	                for(var i=0;i<$('.htWhether',$el).length;i++){
	    		 		$('.htWhether',$el).eq(i).removeClass('step-done').removeClass('step-current');
	    		 	}
	    		 	for(var i=0;i<result.beans.status;i++){
	    		 		$('.htProcessOl li .htWhether',$el).eq(i).addClass('step-done');
	    		 	}
	    		 	if(result.beans.status === 7){
	    		 		$('.htProcessOl .step-last .htWhether').addClass('step-current');
	    		 	}
	    		 	//$('.htWhether',$el).eq(result.beans.status-1).addClass('step-current');
	    		 	htBtnBack(result.beans,result.beans.status);
                },1500);
                
            }else{
                new Dialog({
				    mode: 'tips',
				    delayRmove:1.5, //延迟删除秒数设定 tips默认3秒,非tips默认不关闭。
				    tipsType:'success', //tips类型；可选 success | error，默认普通tips。
				    width:320,
				    height:180,
				    content: '<div style="text-align:center;margin-top:90px">' + result.returnMessage + '</div>'
				});
            }
    		
    	})
    	
    }
    //修改订单
    var editOrderDialog = function(e,item){
    	$(".ui-popup-backdrop, .ui-popup,.ui-popup-modal,.ui-popup-show,.ui-popup-focus").remove();
    	tab.createTab({
            title: '修改工单',
            closeable: 1, //是否可以关闭 0false不可以|1true可以
            className: 'editOrderTab'
        });
        tab.switchTab('修改工单');
        require(['js/order/editOrder'], function(editCD) {
            var result = new editCD({}, editOrderData, tab);
            tab.content(result.content);
        });
    };
    //驳回
    var htRejected = function(){
    	$('.htBtnBack',$el).html('');
    	Util.ajax.getJson(AjaxPath.management + "/order/updateStatus?operation=1&id="+optionsDataID, {}, function(result, isok){
    	//Util.ajax.getJson(AjaxPath.management + "/order/updateStatus?operation=1&id=3", {}, function(result, isok){
    		 if (result.returnCode === "0000") {
    		 	htOrderStatus = result.beans.status
                new Dialog({
				    mode: 'tips',
				    delayRmove:1.5, //延迟删除秒数设定 tips默认3秒,非tips默认不关闭。
				    tipsType:'success', //tips类型；可选 success | error，默认普通tips。
				    width:320,
				    height:180,
				    content: '<div style="text-align:center;margin-top:90px">' + result.beans.sucess + '</div>'
				});
                setTimeout(function(){
	                 //步骤条显示
	                for(var i=0;i<$('.htWhether',$el).length;i++){
	    		 		$('.htWhether',$el).eq(i).removeClass('step-done').removeClass('step-current');
	    		 	}
	    		 	for(var i=0;i<result.beans.status;i++){
	    		 		$('.htWhether',$el).eq(i).addClass('step-done');
	    		 	}
	    		 	if(result.beans.status === 7){
	    		 		$('.htProcessOl .step-last .htWhether').addClass('step-current');
	    		 	}
	    		 	//$('.htWhether',$el).eq(result.beans.status-1).addClass('step-current');
	    		 	htBtnBack(result.beans,result.beans.status);
                },1500);
            }else{
                new Dialog({
				    mode: 'tips',
				    delayRmove:1.5, //延迟删除秒数设定 tips默认3秒,非tips默认不关闭。
				    tipsType:'success', //tips类型；可选 success | error，默认普通tips。
				    width:320,
				    height:180,
				    content: '<div style="text-align:center;margin-top:90px">' + result.returnMessage + '</div>'
				});
            }
    		
    	})
    }
    //指派
    var htAssigned = function(){
    	var config_confirm = {
		    mode: 'confirm', //弹窗模式，可选：normal标准弹窗、tips提示弹窗、confirm确认弹窗；默认normal；
		    title: '工单指派', //弹窗标题；
		    width: '500', //步骤引导组件的宽
            height: '221',
		    content: Util.hdb.compile(AssignedTpl)(), //弹窗内容，tips弹窗和confirm弹窗中只能是string类型。
		    okValue: '确定', //确定按钮的文本 默认是 ‘确定’
		    ok: function() {
	            var htApprovedValidator = new Validator({
	                el: $(".assignedForm"),
	                //submitBtn: $(".ui-dialog-autofocus"), //触发验证的按钮，可不配置
	                dialog: true, //是否弹出验证结果对话框
	                // msgPos: 'top', // 1.0.3版本新增，设置提示信息位置，默认值为top，可选right/bottom/top
	                // pattern: { newCodeName: "^[a-zA-Z][a-zA-Z0-9\\-_]*$" },
	                rules: {
	                    htApprovedName: 'required'
	                },
	                messages: {
	                    htApprovedName: {
	                        required: "请选择指派人！",
	                    }
	                }    
	            });
	            if(!htApprovedValidator.form()) {
	            	return false;
	            }else{
	            	Util.ajax.getJson(AjaxPath.management + "/order/doappoint?id="+optionsDataID+"&userId="+htAssignedSelect.getSelected('userId'), {}, function(result, isok) {
                    
                        if(result.returnCode === "0000"){
                           htBtnBack(result.beans,result.beans.status);
		                    new Dialog({
							    mode: 'tips',
							    delayRmove:1.5, //延迟删除秒数设定 tips默认3秒,非tips默认不关闭。
							    tipsType:'success', //tips类型；可选 success | error，默认普通tips。
							    width:320,
							    height:180,
							    content: '<div style="text-align:center;margin-top:90px">' + result.returnMessage + '</div>'
							});
							
                        }else {
                       		new Dialog({
							    mode: 'tips',
							    delayRmove:1.5, //延迟删除秒数设定 tips默认3秒,非tips默认不关闭。
							    tipsType:'success', //tips类型；可选 success | error，默认普通tips。
							    width:320,
							    height:180,
							    content: '<div style="text-align:center;margin-top:90px">' + result.returnMessage + '</div>'
							});
                        }
                        
                    })
	            }
		        
		    },
		    cancelValue: '取消', //取消按钮的文本 默认是 ‘取消’
		    cancelDisplay: true, //是否显示取消按钮 默认true显示|false不显示
		    quickClose: false, //点击空白处快速关闭 默认false不关闭|true关闭
		    modal: true ,//是否开启模态框状态，即背景遮罩。默认false不开启,confirm弹窗默认状态为true
		    backdropBackground:'#000',//设置遮罩颜色，默认 #000。
		    backdropOpacity:0.4, //设置遮罩透明度，默认 0.4，取值范围：0~1 。
		    beforeOpen: function() {
		    	Util.ajax.getJson(AjaxPath.management + "/order/appoint?userId="+$cookie.get("userId")+"&orderStatus="+htOrderStatus+"&id="+optionsDataID, function(result, isok){
		    	//Util.ajax.getJson(AjaxPath.management + "/order/appoint?userId=1&orderStatus=4", function(result, isok){																				
	        		 if (result.returnCode === "0000") {
	        		 	var addDepartmentData = result.beans;
	        		 	htAssignedSelect = new Select({
		                    el: '.htApprovedSelect', //要绑定的容器
		                    name: 'htApprovedName', //下拉框单元添加name属性
		                    topOption: '请选择',
		                    textField: 'userName',
		                    label: '<span class="color-red">*</span>指派给:',
		                    valueField: 'userName',
		                    loadAtClick: false,
		                    datas: addDepartmentData //数据源与url模式可二选一
		                });
		                $('.htApprovedSelect label').width('22%')
	                	htAssignedSelect.setValue(0);
	                	var telss =
		                htAssignedSelect.on("change",function(e,valueObj){
		                    telss = valueObj.key;
		                });
	        		 	
	        		 	
	                } else {
	               		new Dialog({
						    mode: 'tips',
						    delayRmove:1.5, //延迟删除秒数设定 tips默认3秒,非tips默认不关闭。
						    tipsType:'success', //tips类型；可选 success | error，默认普通tips。
						    width:320,
						    height:180,
						    content: '<div style="text-align:center;margin-top:90px">' + result.returnMessage + '</div>'
						});
	                }
	        		
	        	})
		    }, //弹窗打开之前执行。
		    escClose:true,//esc键快速关闭弹窗，默认为true
		    zIndex:990   // 弹窗的z-index值，默认是1024。
		}
    	var dialog = new Dialog(config_confirm);
    }
	
	//附件  
	//http://192.168.100.193:32032/devops-project/attachment?businessId=820&businessType=require&start=0&limit=5&page=1&_=0.8864726769255207
	var appendixInit = function (){
        var config = {
            el: $('.htAttachment', $el),
            ajax:{    //所有jquery.ajax的配置项均可配置，这些配置将替换底层组件的配置；慎用
                method:'GET'
            },
            field: {
                /* boxType: 'checkbox',*/
                key: 'id',
                items: [
                    {
                        text: '附件名称',
                        title: '',
                        name: 'fileName',
                        className: 'w90',
                        width:200,
                        click: function (e, val, item) {
                            //downloadFile(item);
                        },
                        render: function (item, val) {
                            return  '<a href="http://'+window.location.host+AjaxPath.management+'/attachment/downLoadFile/'+item.id+'">'+val+'</a>';
                        }
                    },
                    {
                        text: '附件大小',
                        title: '',
                        name: 'fileSize',
                        className: 'w90',
                        width:150,
                        render: function (item, val) {
                            if( val < 1024 ){ //如果小于1KB转化成B
                               return '<div >' + val.toFixed(2) + "B"+'<div/>';
                            }else if(val < 1024 * 1024 ){//如果小于1MB转化成KB
                                return '<div >' + (val/1024).toFixed(2) + "KB"+'<div/>';
                            }else if(val < 1024 * 1024 * 1024){ //如果小于1GB转化成MB
                                return '<div >' + (val / (1024 * 1024)).toFixed(2) + "MB"+'<div/>';
                            }else{ //其他转化成GB
                                return '<div >' +(val / (1024 * 1024 * 1024)).toFixed(2) + "GB"+'<div/>';
                            }
                        }
                    },
                    {
                        text: '上传时间',
                        title: '',
                        name: 'createTime',
                        className: 'w90',
                        width:130,
                        render: function (item, val) {
                            return new Date(val).Format("yyyy-MM-dd hh:mm:ss");
                        }
                    }]
            },
            page: {
                customPages: [2, 5, 10, 15, 20, 30, 50], //可选择每页显示多少条
                perPage: 5, //默认每页显示多少条记录
                total: true
            },
            data: {
                url: AjaxPath.management + '/attachment/findAttachment?id='+optionsDataID
            }
        };
        list = new List(config);
        list.search();
    };
    
    //页面元素级权限验证
    /*var getOrderAuthority = function($el){
        //require(['js/btnAuthority'], function(oAuthority){
        //    new oAuthority($el);
        //});
        // Util.ajax.getJson(AjaxPath.auth + '/authority/button/'+ $cookie.get("userId") +'?datas=[{"mo":"3","btnId":""}]', {}, function(result, json){
        //     if(result.returnCode==="0000"){
        //         if(result.beans[0].mo === 0){
        //             projectAuthority = false;
        //         }else {
        //             projectAuthority = true;
        //         }
        //         listInit();
        //     }
        // });
    }*/

    return initialize;
});